﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Net;
using System.Threading;

namespace XMM.Dialoges.WebData
{
    /// <summary>
    /// Interaktionslogik für AmazonSearch.xaml
    /// </summary>
    public partial class AmazonSearch : Window
    {
        string PassedSearchPattern { get; set; }

        Controls.Library.Import_Movie ParentMovieImportControl { get; set; }

        ObservableCollection<AWSInterface.AWSResult> _SearchResults = new ObservableCollection<AWSInterface.AWSResult>();

        public ObservableCollection<AWSInterface.AWSResult> SearchResults
        {
            get
            {
                return _SearchResults;
            }
        }

        private Mutex mutAWSSearch;

        public AmazonSearch(Controls.Library.Import_Movie ctlMovieImportControl, string sSearchPattern)
        {
            InitializeComponent();

            PassedSearchPattern = sSearchPattern;
            ParentMovieImportControl = ctlMovieImportControl;
            mutAWSSearch = new Mutex();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            txtTitle.Text = PassedSearchPattern;
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            setStatus("Durchsuche Amazon-Cloud...", true);

            _SearchResults = new ObservableCollection<AWSInterface.AWSResult>();

            if (txtTitle.Text != String.Empty)
            {
                ParameterizedThreadStart tsAWSSearch = new ParameterizedThreadStart(doAWSSearch);
                Thread thAWSSearch = new Thread(tsAWSSearch);
                thAWSSearch.Start(new object[] { txtTitle.Text });

                //doAWSSearch();
            }
            else
            {
                MessageBox.Show("Bitte geben Sie zuerst einen Titel ein!", "Kein Suchbegriff", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }

            lvResults.ItemsSource = SearchResults;
            lvResults.Items.Refresh();
        }

        private void doAWSSearch(object Data)
        {
            if (mutAWSSearch.WaitOne(1000))
            {
                // Derrive Search-Pattern from Thread-Parameters.
                object[] oaData = (object[])Data;
                string sSearchPattern = (string)oaData[0];

                // Do AWS-Search.
                AWSInterface.AWSSearch oAmazonInterface = new AWSInterface.AWSSearch();
                List<AWSInterface.AWSResult> lResults = oAmazonInterface.searchMovie(sSearchPattern);

                if (lResults != null && lResults.Count > 0)
                {
                    foreach (AWSInterface.AWSResult oResult in lResults)
                    {
                        //_SearchResults.Add(oResult);
                        Dispatcher.Invoke(new addResultCallback(addResult), new object[] { oResult });
                    }
                }

                mutAWSSearch.ReleaseMutex();
            }

            Dispatcher.Invoke(new setStatusCallback(setStatus), new object[] { "Bereit...", false });
        }

        private void addResult(AWSInterface.AWSResult oResult)
        {
            _SearchResults.Add(oResult);
        }

        private delegate void addResultCallback(AWSInterface.AWSResult oResult);

        private void lvResults_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            spnDetails.Visibility = System.Windows.Visibility.Hidden;
            if (lvResults.SelectedIndex > -1)
            {
                AWSInterface.AWSResult oSelectedResult = (AWSInterface.AWSResult)lvResults.SelectedItem;

                if (oSelectedResult != null && oSelectedResult.ASIN != String.Empty)
                {
                    Dispatcher.Invoke(new updateGUICallback(updateGUI), new object[] { oSelectedResult });
                }
            }
        }

        private void updateGUI(AWSInterface.AWSResult oSelectedResult)
        {
            Dispatcher.Invoke(new setStatusCallback(setStatus), new object[] { "Lade Informationen...", true });

            lblTitle.Content = oSelectedResult.Title;
            lblTheatricalRelease.Content = oSelectedResult.TheatricalRelease;
            lblDirector.Content = oSelectedResult.Director;
            txbCast.Text = oSelectedResult.Cast;
            txbPlot.Text = oSelectedResult.Description;

            Dispatcher.Invoke(new setStatusCallback(setStatus), new object[] { "Lade Cover-Art...", true });
            System.Windows.Media.Imaging.BitmapImage oLargeImage = new BitmapImage(new Uri(oSelectedResult.ImageLargeURL, UriKind.Absolute));

            //imgCoverArt.Source = oSelectedResult.Thumbnail;
            Dispatcher.Invoke(new setCoverArtSourceCallback(setCoverArtSource), new object[] { oLargeImage });

            // Toggle Details-Control Visibility.
            spnDetails.Visibility = System.Windows.Visibility.Visible;

            Dispatcher.Invoke(new setStatusCallback(setStatus), new object[] { "Bereit...", false });
        }

        private delegate void updateGUICallback(AWSInterface.AWSResult oSelectedResult);

        private void setCoverArtSource(System.Windows.Media.Imaging.BitmapImage oThumbnail)
        {
            imgCoverArt.Source = oThumbnail;
        }

        private delegate void setCoverArtSourceCallback(System.Windows.Media.Imaging.BitmapImage oThumbnail);

        private void btnApply_Click(object sender, RoutedEventArgs e)
        {
            if (lvResults.SelectedIndex > -1 && lvResults.SelectedItem != null)
            {
                Settings oSettings = new Settings();
                AWSInterface.AWSResult oSelectedResult = (AWSInterface.AWSResult)lvResults.SelectedItem;

                if (oSelectedResult != null && oSelectedResult.ASIN != String.Empty)
                {
                    ParentMovieImportControl.txtTitle.Text = oSelectedResult.Title;
                    ParentMovieImportControl.txtYear.Text = oSelectedResult.TheatricalRelease;
                    ParentMovieImportControl.txtSubtitle.Text = String.Empty;
                    ParentMovieImportControl.txtDirector.Text = oSelectedResult.Director;
                    ParentMovieImportControl.ctlCast.setCast(oSelectedResult.Cast);
                    ParentMovieImportControl.ctlPlot.setPlot(oSelectedResult.Description);
                    if (ParentMovieImportControl.SelectedMediaInfo.UserdefinedMediaInfo == null)
                        ParentMovieImportControl.SelectedMediaInfo.UserdefinedMediaInfo = new Objects.Movie();
                    ((Objects.Movie)ParentMovieImportControl.SelectedMediaInfo.UserdefinedMediaInfo).OnlineMediaID = oSelectedResult.ASIN;

                    try
                    {
                        WebClient oWebClient = new WebClient();
                        oWebClient.DownloadFile(oSelectedResult.ImageLargeURL, oSettings.LibraryDataStorage + "temp\\xmm." + ParentMovieImportControl.SelectedMediaInfo.FileName + ".jpg");
                        ParentMovieImportControl.ctlCoverArt.setCoverImage(oSettings.LibraryDataStorage + "temp\\xmm." + ParentMovieImportControl.SelectedMediaInfo.FileName + ".jpg");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Fehler beim Download des Cover-Images: " + ex.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
                    }

                    Close();

                }
            }
        }

        private void setStatus(string sNewMessage, bool bEnableMarquee)
        {
            lblStatus.Content = sNewMessage;
            pbStatus.IsIndeterminate = bEnableMarquee;
        }

        private delegate void setStatusCallback(string sNewMessage, bool bEnableMarquee);

        private void btnAbort_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }
    }
}
